<?php
    function yes($message="保存成功",$closeCurrent=false,$tabid="",$forward=""){
        $data=array(
            'statusCode'=>200,
            'message'=>$message,
            'tabid'=>$tabid,
            'closeCurrent'=>$closeCurrent,
            'forward'=>$forward,
            'forwardConfirm'=>''
        );
        $rs=json_encode($data);
        exit($rs);
    }
    function error($message="保存失败",$closeCurrent=false,$tabid="",$forward=""){
        $data=array(
            'statusCode'=>300,
            'message'=>$message,
            'tabid'=>$tabid,
            'closeCurrent'=>$closeCurrent,
            'forward'=>$forward,
            'forwardConfirm'=>''
        );
        $rs=json_encode($data);
        exit($rs);
    }
	/**
	 * 格式化字节大小
	 * @param  number $size      字节数
	 * @param  string $delimiter 数字和单位分隔符
	 * @return string            格式化后的带单位的大小
	 */
	function format_bytes($size, $delimiter = '') {
	    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
	    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
	    return round($size, 2) . $delimiter . $units[$i];
	}

    function addToExtend($gid,$cid,$type){
        $gid = is_array($gid)?implode(',',$gid):trim($gid,',');
        $cid = is_array($cid)?$cid:explode( ',',trim($cid,',') );
        $Access = M('auth_extend');
        $del = $Access->where( array('group_id'=>array('in',$gid),'type'=>$type) )->delete();
        $gid = explode(',',$gid);
        $add = array();
        if( $del!==false ){
            foreach ($gid as $g){
                foreach ($cid as $c){
                    if( is_numeric($g) && is_numeric($c) ){
                        $add[] = array('group_id'=>$g,'extend_id'=>$c,'type'=>$type);
                    }
                }
            }
            $Access->addAll($add);
        }
        if ($Access->getDbError()) {
            return false;
        }else{
            return true;
        }
    }
    function default_logo($pic){
        if (empty($pic)) {
            return "/Public/UI/resource/login/default_logo.png";
        }else{
            if (file_exists(".".$pic)) {
                return $pic;
            }else{
                return "/Public/UI/resource/login/default_logo.png";
            }
        }
    }
    function default_banner($pic){
        if (empty($pic)) {
            return "/Public/UI/resource/login/nopic.png";
        }else{
            if (file_exists(".".$pic)) {
                return $pic;
            }else{
                return "/Public/UI/resource/login/nopic.png";
            }
        }
    }
    function getAuthExtend($uid,$type,$session){
        if ( !$type ) {
            return false;
        }
        if ( $session ) {
            $result = session($session);
        }
        if ( $uid == UID && !empty($result) ) {
            return $result;
        }
        $prefix = C('DB_PREFIX');
        $result = M()
            ->table($prefix."auth_group_access".' g')
            ->join($prefix."auth_extend".' c on g.group_id=c.group_id')
            ->where("g.uid='$uid' and c.type='$type' and !isnull(extend_id)")
            ->getfield('extend_id',true);
        if ( $uid == UID && $session ) {
            session($session,$result);
        }
        return $result;
    }

    function getAuthCategories($uid){
        return getAuthExtend($uid,1,'AUTH_CATEGORY');
    }

    function getCategoryOfGroup($gid){
        return getExtendOfGroup($gid,1);
    }

    function getExtendOfGroup($gid,$type){
        if ( !is_numeric($type) ) {
            return false;
        }
        return M("auth_extend")->where( array('group_id'=>$gid,'type'=>$type) )->getfield('extend_id',true);
    }

    function GetFieldMake($dtype, $fieldname, $dfvalue, $mxlen)
    {
        $fields = array();
        if($dtype == "int" || $dtype == "datetime")
        {
            if($dfvalue == "" || preg_match("#[^0-9-]#", $dfvalue))
            {
                $dfvalue = 0;
            }
            $fields[0] = " `$fieldname` int(11) NOT NULL default '$dfvalue';";
            $fields[1] = "int(11)";
        }
        else if($dtype == "color")
        {
            if(empty($dfvalue)) $dfvalue = '';
            $fields[0] = " `$fieldname` char(10) NOT NULL default '$dfvalue';";
            $fields[1] = "char(10)";
        }
        else if($dtype == "imgfile"){
            $fields[0] = " `$fieldname` text;";
            $fields[1] = "text";
        }
        else if($dtype == "float")
        {
            if($dfvalue == "" || preg_match("#[^0-9\.-]#", $dfvalue))
            {
                $dfvalue = 0;
            }
            $fields[0] = " `$fieldname` float NOT NULL default '$dfvalue';";
            $fields[1] = "float";
        }
        else if($dtype == "img" || $dtype == "media" || $dtype == "addon")
        {
            if(empty($dfvalue)) $dfvalue = '';
            if($mxlen=="") $mxlen = 200;
            if($mxlen > 255) $mxlen = 100;
            $fields[0] = " `$fieldname` varchar($mxlen) NOT NULL default '$dfvalue';";
            $fields[1] = "varchar($mxlen)";
        }
        else if($dtype == "multitext" || $dtype == "htmltext")
        {
            $fields[0] = " `$fieldname` mediumtext;";
            $fields[1] = "mediumtext";
        }
        else if($dtype=="textdata")
        {
            if(empty($dfvalue)) $dfvalue = '';
            $fields[0] = " `$fieldname` varchar(100) NOT NULL default '';";
            $fields[1] = "varchar(100)";
        }
        else if($dtype=="textchar")
        {
            if(empty($dfvalue)) $dfvalue = '';
            
            $fields[0] = " `$fieldname` char(100) NOT NULL default '$dfvalue';";
            $fields[1] = "char(100)";
        }
        else if($dtype=="checkbox")
        {
            $dfvalue = str_replace(',',"','",$dfvalue);
            $dfvalue = "'".$dfvalue."'";
            $fields[0] = " `$fieldname` SET($dfvalue) NULL;";
            $fields[1] = "SET($dfvalue)";
        }
        else if($dtype=="select" || $dtype=="radio")
        {
            $dfvalue = str_replace(',', "','", $dfvalue);
            $dfvalue = "'".$dfvalue."'";
            $fields[0] = " `$fieldname` enum($dfvalue) NULL;";
            $fields[1] = "enum($dfvalue)";
        }
        else
        {
            if(empty($dfvalue))
            {
                $dfvalue = '';
            }
            if(empty($mxlen))
            {
                $mxlen = 100;
            }
            if($mxlen > 255)
            {
                $mxlen = 250;
            }
            $fields[0] = " `$fieldname` varchar($mxlen) NOT NULL default '$dfvalue';";
            $fields[1] = "varchar($mxlen)";
        }
        return $fields;
    }


    function get_file_md5($file){
        return $md5file = md5_file($file);
    }

    function get_wechat_token(){
        $token ='w'.'ww_'.'m'.'c'.'l'.'y_c'.'c_'.get_randomstr(10);
        return $token;
    }
    function insert_wechat_token($file,$line,$txt){
        @chmod($file, 0777);
        if(!$fileContent = @file($file)) exit('文件不存在');
        $lines       = count($fileContent);
        if($line >= $lines) $line = $lines;
        $fileContent[$line].=$txt;
        $newContent = '';
        foreach($fileContent as $v){
            $newContent.= $v;
        }
        if(!file_put_contents($file,$newContent)) exit('无法写入数据');
    }

    function authCheck($rule,$uid,$type=1, $mode='url', $relation='or'){
        $auth=new \Think\Auth();
        $groups=$auth->getGroups($uid);
        if(in_array($groups[0]['id'], C('ADMINISTRATOR'))){
            return true;
        }else{          
            return $auth->check($rule,$uid,$type,$mode,$relation)?true:false;
        }
    }

    function get_auth_moduleName($mid=1){
        return M('auth_modules')->where(array('id'=>$mid))->getField('moduleName');
    }

    function nodeForLayer($node, $access = null, $pid = 0) {
        if($node == '') return array();
        $arr = array();

        foreach ($node as $v) {
            if (is_array($access)) {
                
                $v['access'] =in_array($v['id'], $access)? 1 : 0;
            }
            if ($v['pid'] == $pid) {
                $v['child'] = nodeForLayer($node, $access, $v['id']);
                $arr[] =$v;
            }
        }
        return $arr;
    }
    function get_flags($flag){
        $flags=explode(',', $flag);
        $flagtype = getArrayOfItem('flagtype');//文档属性
        $flagStr = array();   
        foreach ($flags as $k => $v) {
            foreach ($flagtype as $key => $value) {
                if ($v == $key) {
                    $flagStr[] = $value;
                }
            }       
         }
        return implode(',', $flagStr);
    }
    function flag2Str($flag, $delimiter=' ', $iskey = false, $isarray = false) {
        if (empty($flag)) {
            return $isarray? array(): '';
        }
        $flagStr = array();
        $flagtype = getArrayOfItem('flagtype');//文档属性
        foreach ($flagtype as $k => $v) {
            if ($flag & $k) {
                $flagStr[] = $iskey? $k : $v;
            }
        }
        if ($isarray) {
            return $flagStr;
        } else {
            return implode($delimiter, $flagStr);
        }
    }
    function delDirAndFile($dirName, $bFlag = false ) {
        if ( $handle = opendir( "$dirName" ) ) {
            while ( false !== ( $item = readdir( $handle ) ) ) {
                if ( $item != "." && $item != ".." ) {
                    if ( is_dir( "$dirName/$item" ) ) {
                        delDirAndFile("$dirName/$item", $bFlag);
                    } else {
                        unlink( "$dirName/$item" );
                    }
                }
            }
            closedir( $handle );
            if($bFlag) rmdir($dirName);
        }
    }
?>